package com.gin.no_gay_alliance.callback;

import android.util.Log;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 缓存用数据包
 *
 * @param <T>
 */
public class Bundle<T> {
    /**
     * 过期时间 不填默认60秒
     */
    public final long expires;
    /**
     * 数据
     */
    public final T data;

    public Bundle(T data) {
        this(data, 1, TimeUnit.MINUTES);
    }

    public Bundle(T data, long expires) {
        this.expires = expires;
        this.data = data;
    }

    public Bundle(T data, long time, TimeUnit unit) {
        this(data, System.currentTimeMillis() / 1000 + unit.toSeconds(time));
    }

    /**
     * 检查缓存
     *
     * @param ignoreCache 是否忽略缓存
     * @param cache       缓存对象
     * @param key         key
     * @param callback    回调方法
     * @return 是否应用了缓存
     */
    public static <K, T> boolean checkCache(boolean ignoreCache, HashMap<K, Bundle<T>> cache, K key, Callback<T> callback) {
        clearCache(cache);

        // 如果不忽略缓存，且缓存为有效数据，使用缓存
        if (!ignoreCache && cache.containsKey(key)) {
            Bundle<T> bundle = cache.get(key);
            if (bundle != null) {
                T data = bundle.data;
                Log.d(data.getClass().getSimpleName(), "缓存命中: " + key);
                callback.onSuccess(data);
                return true;
            }
        }
        return false;
    }

    public static <K, T> void clearCache(HashMap<K, Bundle<T>> cache) {
        int size1 = cache.size();
        cache.entrySet().removeIf(next -> {
            boolean needClear = !next.getValue().isAvailable();
            if (needClear) {
                Log.d(next.getValue().data.getClass().getSimpleName(), "清理失效缓存: " + next.getKey());
            }
            return needClear;
        });
        int count = size1 - cache.size();
        if (count > 0) {
            Log.d("CacheManager", "清理失效缓存: " + count + "个");
        }
    }

    /**
     * 缓存数据是否可用
     *
     * @return 缓存是否可用
     */
    public boolean isAvailable() {
        return System.currentTimeMillis() / 1000 <= expires;
    }

}